﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<Python.h>
#include<QFileDialog>
#include<QLabel>
#include <QAction>
#include <QString>
#include <QImage>
#define QT_NO_OPENGL
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle(tr("Software"));
    creatActions();
    this->previousImage = new QImage();
    this->nextImage = new QImage();
}

MainWindow::~MainWindow()
{
    delete ui;
}
//修改打开文件格式限制修改函数中getOpenDialog()第四个参数
//打开文件
void MainWindow::open()
{
    if(okToOpen()){
        QString fileName= QFileDialog::getOpenFileName(this,tr("open file"),"C:\\","Image files (*.bmp *.jpg *.pbm *.pgm *.png *.ppm *.xbm *.xpm);;All files (*.*)");
        if(!fileName.isEmpty())
            loadFile(fileName);
    }
}
//save slot
void MainWindow::save()
{
    if(okToSave())saveFile();
}
//test slot
void MainWindow::test()
{
    setStatusTip(tr("Loading..."));
    if(okToTest())testFile();
}
//creat a square slot
//show dialog
void MainWindow::creatASquare()
{
    if(okToCreatSquare()) creatSquareDialog->show();
}
void MainWindow::judgeASquare(int i)
{
    operationType=i;
    creatSquare();
    squareNumber++;
    setStatusTip(tr("Creating a new square is done."));
}
//receive square value from dialog and creat
void MainWindow::receiveCreatSquare(int x_Value, int y_Value, int side_Length)
{
    //receive value
    squareXValue=x_Value;
    squareYValue=y_Value;
    squareSideLength=side_Length;
    judgeSceneDialog->receiveCreatSquare(squareXValue,squareYValue,squareSideLength,squareNumber);
    QString str_x=QString::number(squareXValue);
    QString str_y=QString::number(squareYValue);
    QString str_sl=QString::number(squareSideLength);
    QString str_show="Creat a "+str_sl+"*"+str_sl+" square at "+str_x+", "+str_y;
    setStatusTip(str_show);
    //creat with python
    operationType=0;
    creatSquare();
    judgeSceneDialog->show();
    setStatusTip(QString::number(squareNumber));
}
//在此函数中修改setStatusTip()内的内容即为修改状态栏的内容；
//此函数中的setShortcut用于设置快捷键；
//设置了打开保存test与按钮的链接,test has no shortcut
void MainWindow::creatActions()
{
    ui->actionOpen->setShortcut(QKeySequence::Open);
    ui->actionOpen->setStatusTip(tr("Open a file"));
    connect(ui->actionOpen,SIGNAL(triggered()),this,SLOT(open()));

    ui->actionSave->setShortcut(QKeySequence::Save);
    ui->actionSave->setStatusTip(tr("Save a file"));
    connect(ui->actionSave,SIGNAL(triggered()),this,SLOT(save()));

    ui->actionExit->setShortcut(tr("Ctrl+Q"));
    ui->actionExit->setStatusTip(tr("Exit the application"));
    connect(ui->actionExit,SIGNAL(triggered()),this,SLOT(close()));

    ui->actionGO->setStatusTip(tr("Do test"));
    connect(ui->actionGO,SIGNAL(triggered()),this,SLOT(test()));

    this->creatSquareDialog=new CreatSquareDialog;
    connect(ui->actionCreatSquare,SIGNAL(triggered()),this,SLOT(creatASquare()));
    connect(creatSquareDialog,SIGNAL(sendCreatSquare(int,int,int)),this,SLOT(receiveCreatSquare(int,int,int)));
    connect(this,SIGNAL(sendSquareRange(int,int)),creatSquareDialog,SLOT(receiveSquareRange(int,int)));

    this->judgeSceneDialog=new JudgeSceneDialog;
    connect(judgeSceneDialog,SIGNAL(judgeResult(int)),this,SLOT(judgeASquare(int)));
}
//判断是否可以打开新文件
bool MainWindow::okToOpen()
{
    if(isRightEmpty==false){
        setStatusTip(tr("Please save the picture and try again."));
        return false;
    }
    return true;
}
//判断是否ok to save
bool MainWindow::okToSave()
{
    if(isRightEmpty==true){
        setStatusTip(tr("Nothing to save."));
        return false;
    }
    return true;
}
//判断是否可以test
bool MainWindow::okToTest()
{
    if(isRightEmpty==false){
        setStatusTip(tr("Please save the picture and try again."));
        return false;
    }
    if(isLeftEmpty==true){
        setStatusTip(tr("Nothing to test.Please open a file."));
        return false;
    }
    if(squareNumber<MAXNUMBER){
        setStatusTip(tr("Squares are not enough."));
        return false;
    }
    return true;
}
bool MainWindow::okToCreatSquare()
{
    if(isRightEmpty==false){
        setStatusTip(tr("Please save the picture and try again."));
        return false;
    }
    if(isLeftEmpty==true){
        setStatusTip(tr("Please open a file and try again."));
        return false;
    }
    if(squareNumber>=MAXNUMBER){
        setStatusTip(tr("Squares are enough.Please test."));
        return false;
    }
    return true;
}
//显示打开的图片
bool MainWindow::loadFile(const QString &fileName)
{
    if(!(previousImage->load(fileName)))
            {
                statusBar()->showMessage(tr("File loaded false"));
                delete previousImage;
                return false;
            }
    previousImage->save("./temp.jpg","JPG");
    emit sendSquareRange(previousImage->width(),previousImage->height());
    QPixmap pixmap = QPixmap::fromImage(previousImage->scaled(ui->previousLabel->size(), Qt::KeepAspectRatio));
    ui->previousLabel->setPixmap(pixmap);
    setCurrentFile(fileName);
    isLeftEmpty=false;
    setStatusTip(tr("File loaded."));
    squareNumber=0;
    operationType=0;
    return true;
}
//保存文件
bool MainWindow::saveFile()
{
    QString fileName=QFileDialog::getSaveFileName(this,tr("Save File"),".","Image files (*.bmp *.jpg *.pbm *.pgm *.png *.ppm *.xbm *.xpm)");
    if(fileName.isEmpty()){
        setStatusTip(tr("FileName Error!"));
        return false;
    }
    if(!(nextImage->save(fileName))){
        setStatusTip(tr("Can't save file."));
        return false;
    }
    else {
        setStatusTip(tr("File saved."));
        isLeftEmpty=true;
        isRightEmpty=true;
        squareNumber=0;
        operationType=0;
        return true;
    }
}
//testFile()from python
bool MainWindow::testFile()
{
    setStatusTip(leftFile);
    //return false;
    //初始化python模块
        Py_Initialize();
        if ( !Py_IsInitialized() ) return false;
        //导入test.py模块
        PyRun_SimpleString("import sys");
        PyRun_SimpleString("sys.path.append('/home/sssss/Software/')");
        PyObject* pModule = PyImport_ImportModule("ab");
        if (!pModule) {
                    setStatusTip(tr("Cant open python file!\n"));
                    return false;
                }
        //获取模块中的test函数
       PyObject* pFuntest= PyObject_GetAttrString(pModule,"test");
       if(!pFuntest){
               setStatusTip(tr("Get function hello failed"));
               return false;
           }
       char*  ch;
           QByteArray ba = leftFile.toLatin1();
           ch=ba.data();

        //调用test函数
            PyObject* args = PyTuple_New(1);   // 1个参数
            PyObject* arg1 = Py_BuildValue("s",ch);    // set参数
            PyTuple_SetItem(args, 0, arg1);

            // 调用函数
            PyObject* pRet = PyObject_CallObject(pFuntest, args);
//            char* nextName;
//            PyArg_ParseTuple(pRet,"s",&nextName);
//            nextImage->load(nextName);
        //结束，释放python

            nextImage->load("/home/sssss/build-Software-Desktop_Qt_5_10_0_GCC_64bit-Debug/res.jpg");
            QPixmap pixmap = QPixmap::fromImage(nextImage->scaled(ui->nextLabel->size(), Qt::KeepAspectRatio));
            ui->nextLabel->setPixmap(pixmap);
            if(nextImage)
                setStatusTip(tr("Test success."));
            else
                setStatusTip(tr("The result is NULL!"));
            isRightEmpty=false;
            return true;
}
//creat a square with python
bool MainWindow::creatSquare()
{
    //初始化python模块
        Py_Initialize();
        if ( !Py_IsInitialized() ) return false;
        //导入test.py模块
        PyRun_SimpleString("import sys");
        PyRun_SimpleString("sys.path.append('/home/sssss/Software/')");
        PyObject* pModule = PyImport_ImportModule("ab");
        if (!pModule) {
                    setStatusTip(tr("Cant open python file!\n"));
                    return false;
                }
        //获取模块中的test函数
       PyObject* pFuncreatSquare= PyObject_GetAttrString(pModule,"creatSquare");
       if(!pFuncreatSquare){
               setStatusTip(tr("Get function creatSquare failed"));
               return false;
           }
        //调用test函数
            PyObject* args = PyTuple_New(4);   // 4个参数
            PyObject* arg1 = Py_BuildValue("i",squareXValue);    // set参数
            PyObject* arg2 = Py_BuildValue("i",squareYValue);
            PyObject* arg3 = Py_BuildValue("i",squareSideLength);
            PyObject* arg4 = Py_BuildValue("i",operationType);
            PyTuple_SetItem(args, 0, arg1);
            PyTuple_SetItem(args, 1, arg2);
            PyTuple_SetItem(args, 2, arg3);
            PyTuple_SetItem(args, 3, arg4);

            // 调用函数
            PyObject* pRet = PyObject_CallObject(pFuncreatSquare, args);
//            char* nextName;
//            PyArg_ParseTuple(pRet,"s",&nextName);
//            nextImage->load(nextName);
        //结束，释放python

/*            nextImage->load("/home/sssss/build-Software-Desktop_Qt_5_10_0_GCC_64bit-Debug/res.jpg");
            QPixmap pixmap = QPixmap::fromImage(nextImage->scaled(ui->nextLabel->size(), Qt::KeepAspectRatio));
            ui->nextLabel->setPixmap(pixmap);
            if(nextImage)
                setStatusTip(tr("Test success."));
            else
                setStatusTip(tr("The result is NULL!"));
            isRightEmpty=false;*/
            previousImage->load("/home/sssss/build-Software-Desktop_Qt_5_10_0_GCC_64bit-Debug/temp.jpg");
            if(previousImage)
                setStatusTip(tr("Creat success."));
            else
                setStatusTip(tr("Creat false"));
            QPixmap pixmap = QPixmap::fromImage(previousImage->scaled(ui->previousLabel->size(), Qt::KeepAspectRatio));
            ui->previousLabel->setPixmap(pixmap);
            return true;
}
//实现窗口名根据打开文件名称来显示
void MainWindow::setCurrentFile(const QString &fileName)
{
    leftFile=fileName;
    setWindowModified(false);
    QString shownName=tr("Untitled");
    if(!leftFile.isEmpty()){
        shownName=strippedName(leftFile);
    }
    setWindowTitle(tr("%1[*]-%2").arg(shownName).arg(tr("Software")));
}
//根据文件名设置窗口名时调用的一个函数
QString MainWindow::strippedName(const QString &fullfileName)
{
    return QFileInfo(fullfileName).fileName();
}
